package com.ansion.commonchat.util;

import android.content.SharedPreferences;
import android.text.TextUtils;

import com.ansion.basedb.dao.LoginedUserMgr;
import com.ansion.basedb.dao.model.CurrentUser;
import com.ansion.log.VLog;
import com.ansion.utils.PhoneNumberHelper2;
import com.ansion.utils.ResourceUtils;
import com.ansion.utils.phone.CocoPhoneNumber;


public class FormatUserIdHelper {

    private static final String TAG = FormatUserIdHelper.class.getSimpleName();


    /**
     * 返回 保存在应用内的 phone,uid键值对。如果返回 >0,表示合法的uid
     * 
     * @param phone
     * @return
     */
    public static long getUidByPhone(String phone) {

        long format = getFormatUseridFromSp(phone);

        return format;

    }



    /**
     * 获取sp中保存的FormatUserid ，如果是 0表示，取不到
     * 
     * @param countryCode
     * @param originalPhone
     * @return
     */
    public static long getFormatUserid(int countryCode, String originalPhone) {

        long format = getFormatUseridFromSp(originalPhone);

        if (format <= 0) {
            try{

                CocoPhoneNumber cocoPhone= PhoneNumberHelper2.getCocoNumber(countryCode, originalPhone);
                if (cocoPhone!=null&&!TextUtils.isEmpty(cocoPhone.getPhone())){
                    format =Long.parseLong(cocoPhone.getPhone());
                }

            }catch (Exception e){
                VLog.e(TAG,e);
                format=0;
            }

            if (format<=0){
                format=0;
            }
            saveFormatUseridSp(originalPhone, format);
        }

        return format;

    }

    private static void saveFormatUseridSp(String originalPhone, long formatPhone) {

        SharedPreferences sp = getFormatUseridSharedPreferences();
        if (sp != null) {
            SharedPreferences.Editor editor = sp.edit();
            editor.putLong(originalPhone, formatPhone);
            editor.commit();
        }
    }

    /**
     * 获取sp中保存的FormatUserid ，如果是－1表示，取不到
     * 
     * @param originalPhone
     * @return
     */
    private static long getFormatUseridFromSp(String originalPhone) {

        long value = -1;
        SharedPreferences sp = getFormatUseridSharedPreferences();
        if (sp != null) {
            value = sp.getLong(originalPhone, -1);
        }
        return value;
    }

    private static SharedPreferences getFormatUseridSharedPreferences() {

        CurrentUser user = LoginedUserMgr.getCurrentLoginedUser();
        if (user == null || user.getUserId() < 0) {
            return null;
        }
        //todo update to mmkv
        return  ResourceUtils.getSharedPreferences("FormatUserid_" + user.getUserId());
    }

}
